package com.nobuyme.box.util;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import android_serialport_api.SerialPort;
import android_serialport_api.SerialPortController;
import android_serialport_api.SerialPortFinder;

/**
 * Created by Administrator on 2017/6/22.
 */

public class UICommon {
    private static final String TAG = "UICommon";
    private static final int SERIAL_PORT_RECEIVE_DATA		      = 1;

    public static final int CMD_SUCCESS		      = 1;
    public static final int CMD_FAIL		          = -1;




    public static final int ERROR_STATUS_NO_FAULTS	     = 0;   //0:没有故障       其他:有故障
    public static final int ERROR_STATUS_HAVE_FAULTS	      = 1; //0:没有故障       其他:有故障

    public static final int STATUS_FREE		             = 1;
    public static final int STATUS_BUSY		             = 2;
    public static final int STATUS_WAIT_TAKE_GOODS		 = 3;


    public static final int OPEN_SERIAL_PORT		      = 0;
    public static final int SEND_RECIVE_DATA		      = 1;
    public static final int CMD_TEST_SLOT_END		      = 200;
    public static final int CMD_LATTICE_SET_END		      = 201;


    public static final String PORT ="dev/ttymxc1";
    public static final String PORT2 ="dev/ttymxc2";
    public static final int TATEL =9600;

    private static UICommon  m_Instance = null;
    private volatile boolean m_isTestingSlotNo = false;
    private volatile int m_iShipSlotNo = 0;

    private volatile boolean m_isSettingLattice = false;
    private volatile boolean m_isCheckboxInVaild = false;
    private volatile int m_iRow = 0;

    private volatile String m_strComPath = null;

    private volatile boolean m_bIsSendData = false;
    private SerialPort m_SerialPort = null;
    private SerialPortFinder m_SerialPortFinder = null;
    private InputStream m_InputStream = null;
    private OutputStream m_OutputStream = null;
    private ReadThread m_ReadThread = null;
    private Handler m_ReceiveHandler = null;

    private volatile String m_readData = "";
    private List<Integer> m_slotNoTestList = null;
    private List<Integer> m_columnList = null;


    public void setHandler(Handler receiveHandler) {
        m_ReceiveHandler = receiveHandler;
    }


    public static synchronized UICommon getInstance() {
        if (null == m_Instance) {
            m_Instance = new UICommon();
        }
        return m_Instance;
    }

    public void reqWriteDataShipTest(String addr, List<Integer> slotNoList) {
        if ((null == slotNoList) || (slotNoList.size() < 1)) {
            return;
        }
        m_slotNoTestList = slotNoList;
        m_isTestingSlotNo = true;
        m_iShipSlotNo = slotNoList.get(0);
        writeData(DriveControlLattice.getInstance().LatticeOnOff(Integer.toHexString(Integer.valueOf(addr)),slotNoList.get(0)));
    }

    public void reqWriteDataLatticeSet(boolean inVaild, int row, String addr, List<Integer> columnList) {
        if ((null == columnList) || (columnList.size() < 1)) {
            return;
        }
        m_columnList = columnList;
        m_isSettingLattice = true;
        m_isCheckboxInVaild = inVaild;
        m_iRow = row;
        writeData(DriveControlLattice.getInstance().LatticeNumSet(m_isCheckboxInVaild, Integer.toHexString(Integer.valueOf(addr)), Integer.toHexString(m_iRow), Integer.toHexString(columnList.get(0))));
    }

    public SerialPortFinder getSerialPortFinder() {
        return SerialPortController.getInstance().getSerialPortFinder();
    }

    public void openSeri(String port ,int tatel) {
        if(port.equals("dev/ttymxc1")){
        }else{
        }

        try {
            m_SerialPort = new SerialPort(new File(port), tatel,0);
            m_OutputStream = m_SerialPort.getOutputStream();
            m_InputStream = m_SerialPort.getInputStream();

            if (null == m_ReadThread || !m_ReadThread.isAlive()) {
                m_ReadThread = new ReadThread();
                m_ReadThread.setName("ReadThread");
                m_ReadThread.setRun(true);
                m_ReadThread.start();
            }

            if (m_ReceiveHandler != null) {
                Message message = m_ReceiveHandler.obtainMessage();
                message.what = OPEN_SERIAL_PORT;
                message.arg1 = CMD_SUCCESS;
                m_ReceiveHandler.sendMessage(message);
            }
        } catch (SecurityException e) {
            if (m_ReceiveHandler != null) {
                Message message = m_ReceiveHandler.obtainMessage();
                message.what = OPEN_SERIAL_PORT;
                message.arg1 = CMD_FAIL;
                message.obj = e.toString();
                m_ReceiveHandler.sendMessage(message);
            }
        }  catch (IOException e) {
            e.printStackTrace();
            if (m_ReceiveHandler != null) {
                Message message = m_ReceiveHandler.obtainMessage();
                message.what = OPEN_SERIAL_PORT;
                message.arg1 = CMD_FAIL;
                message.obj = e.toString();
                m_ReceiveHandler.sendMessage(message);
            }

        }
    }

    /**
     * 关闭串口
     */
    public void closeSerialPort() {
        if (m_ReadThread != null) {
            m_ReadThread.setRun(false);
            m_ReadThread.interrupt();
            m_ReadThread.destroy();
        }
        if (m_OutputStream != null) {
            try {
                m_OutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            m_OutputStream = null;
        }

        if (m_InputStream != null) {
            try {
                m_InputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            m_InputStream = null;
        }

        if (m_SerialPort != null) {
            m_SerialPort.close();
            m_SerialPort.closeStream();
            m_SerialPort = null;
        }
    }
    public void setComPath(String comPath) {
        m_strComPath = comPath;
    }

    public String getComPath() {
        return m_strComPath;
    }

    public void writeData(byte[] bytes) {
//        Log.i(TAG, "writeData() bytes: "+TcnUtility.bytesToHexString(bytes));
        if(null == bytes) {
//            EasyToast.showToast(MyApplication.getAppContext(), "writeData bytes is null");
            return;
        }
        m_readData = "";
        try {
            if (null != m_OutputStream) {
                m_OutputStream.write(bytes);
                m_OutputStream.flush();
            }
//            EasyToast.showToast(MyApplication.getAppContext(), "xie ru shuju chenggong");
        } catch (IOException e) {
//            EasyToast.showToast(MyApplication.getAppContext(), "writeData 向串口写数据错误 e：" + e);
        }
    }

    private void onHandleCardData(String cmdData) {
        Log.i(TAG, "onHandleCardData() cmdData: "+cmdData);
        Message message = m_ReceiveHandler.obtainMessage();
        if ((null == cmdData) || (cmdData.length() < 20)) {
            message.what = SEND_RECIVE_DATA;
            message.arg1 = -1;
            message.obj = cmdData;
            m_ReceiveHandler.sendMessage(message);
            return;
        }
        String addr = cmdData.substring(6,8);
        int iAddr = Integer.valueOf(addr,16);
        String sendData = "接收数据："+cmdData;
        if (DriveControlLattice.getInstance().getCmdType() == DriveControlLattice.CMD_QUERY_BASIC) {
            String tmpdata = cmdData.substring(8,14);
            sendData = "组号："+addr+" 接收数据："+cmdData+" 设备版本号："+tmpdata.substring(0,2)+" 故障代码："+tmpdata.substring(2,4);
        } else if (DriveControlLattice.getInstance().getCmdType() == DriveControlLattice.CMD_QUERY_CABINET) {
            String tmpdata = cmdData.substring(8,10);
            if (tmpdata.equals("00")) {
                sendData = "组号："+addr+" 接收数据："+cmdData+" 状态："+tmpdata+" 不存在";
            } else {
                sendData = "组号："+addr+" 接收数据："+cmdData+" 状态："+tmpdata+" 存在";
            }
        } else if (DriveControlLattice.getInstance().getCmdType() == DriveControlLattice.CMD_SCAN_LIGHT_SET) {
            sendData = "组号："+addr+" 接收数据："+cmdData;
        } else if (DriveControlLattice.getInstance().getCmdType() == DriveControlLattice.CMD_CABINETNO_SET) {
            sendData = "组号："+addr+" 接收数据："+cmdData;
            if (m_isSettingLattice) {
                if (m_columnList != null) {
                    if (m_columnList.size() > 0) {
                        m_columnList.remove(0);
                        if (m_columnList.size() > 0) {
                            writeData(DriveControlLattice.getInstance().LatticeNumSet(m_isCheckboxInVaild,addr, Integer.toHexString(m_iRow), Integer.toHexString(m_columnList.get(0))));
                        } else {
                            m_isSettingLattice = false;
                            message.what = CMD_LATTICE_SET_END;
                            m_ReceiveHandler.sendMessage(message);
                        }
                    } else {
                        m_isSettingLattice = false;
                    }
                } else {
                    m_isSettingLattice = false;
                }
            }
        } else if (DriveControlLattice.getInstance().getCmdType() == DriveControlLattice.CMD_CABINETNO_ON) {
            String tmpdata = cmdData.substring(8,10);
            if (tmpdata.equals("00")) {
                sendData = "组号："+addr+" 接收数据："+cmdData+" 状态："+tmpdata;
            } else if (tmpdata.equals("01")) {
                sendData = "组号："+addr+" 接收数据："+cmdData+" 状态："+tmpdata+" Nmos管损坏";
            } else if (tmpdata.equals("02")) {
                sendData = "组号："+addr+" 接收数据："+cmdData+" 状态："+tmpdata+" Pmos管损坏";
            } else if (tmpdata.equals("03")) {
                sendData = "组号："+addr+" 接收数据："+cmdData+" 状态："+tmpdata+" 为电磁阀损坏 没有电流";
            } else if (tmpdata.equals("04")) {
                sendData = "组号："+addr+" 接收数据："+cmdData+" 状态："+tmpdata;
            } else if (tmpdata.equals("05")) {
                sendData = "组号："+addr+" 接收数据："+cmdData+" 状态："+tmpdata+" 柜号不存在";
            } else if (tmpdata.equals("06")) {
                sendData = "组号："+addr+" 接收数据："+cmdData+" 状态："+tmpdata+" 为电流过大";
            } else {

            }
            if (m_isTestingSlotNo) {
                if (m_slotNoTestList != null) {
                    if (m_slotNoTestList.contains(Integer.valueOf(m_iShipSlotNo))) {
                        m_slotNoTestList.remove(Integer.valueOf(m_iShipSlotNo));
                    }
                    if (m_slotNoTestList.size() > 0) {
                        m_iShipSlotNo = m_slotNoTestList.get(0);
                        writeData(DriveControlLattice.getInstance().LatticeOnOff(addr,m_iShipSlotNo));
                    } else {
                        m_isTestingSlotNo = false;
                        message.what = CMD_TEST_SLOT_END;
                        m_ReceiveHandler.sendMessage(message);
                    }
                } else {
                    m_isTestingSlotNo = false;
                }
            }
        } else {

        }
        message.what = SEND_RECIVE_DATA;
        message.arg1 = iAddr;
        message.obj = sendData;
        m_ReceiveHandler.sendMessage(message);
    }


    private class ReadThread extends Thread {

        private boolean bIsRun;

        public boolean getRun() {
            return bIsRun;
        }

        public void setRun(boolean bRun) {
            this.bIsRun = bRun;
        }

        @Override
        public void run() {
            super.run();

            if (null == m_InputStream) {
//                Log.e(TAG, "readthread m_InputStream is null");
                return;
            }
//            Log.i(TAG, "进入readthread啦------getRun(): " + getRun());
            byte[] buffer = null;
            String read = "";
            int byteCount = 0;
            m_bIsSendData = false;
            while (bIsRun) {

                try {
                    buffer = new byte[256];
                    byteCount = m_InputStream.read(buffer);
                    if (byteCount > 0) {
                        read = TcnUtility.bytesToHexString(buffer, byteCount);;
                        m_bIsSendData = true;
                    } else {
                        read = "";
                    }

                    if (read.length() > 0) {
                        m_readData += read;
                        if (m_handler != null) {
                            Message message = m_handler.obtainMessage();
                            message.what = SERIAL_PORT_RECEIVE_DATA;
                            message.obj = m_readData;
                            m_handler.removeMessages(SERIAL_PORT_RECEIVE_DATA);
                            m_handler.sendMessageDelayed(message,300);
                        } else {
//                            Log.e(TAG, "m_ReceiveHandler is null" );
                        }
                    }

                } catch (IOException e) {
//                    Log.e(TAG, "ReadThread IOException e: " + e);
                    e.printStackTrace();
                    break;
                }
            }
        }
    }

    private Handler m_handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SERIAL_PORT_RECEIVE_DATA:
                    onHandleCardData((String)msg.obj);
                    break;
                default:
                    break;
            }
        }
    };
}
